import axios from "axios";
import type { AxiosInstance } from "axios";
import { normalizeError } from "./normalizeError";

const service: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_API_BASE || "/api",
  timeout: 30000,
  withCredentials: false,
  headers: {
    // 不在全局强制指定 Content-Type，交由每次请求或浏览器自动决定
  },
});

// 统一错误规范化，其余逻辑在上层封装（request.ts）处理
service.interceptors.request.use(
  (config) => {
    // 若为 FormData，删除任何预设的 Content-Type，交由浏览器自动附带 boundary
    try {
      if (config.data instanceof FormData) {
        if (config.headers) {
          delete (config.headers as any)["Content-Type"]
          delete (config.headers as any)["content-type"]
        }
      }
    } catch {}
    return config
  },
  (err) => Promise.reject(normalizeError(err)),
);

service.interceptors.response.use(
  (resp) => resp,
  (err) => Promise.reject(normalizeError(err)),
);

export default service;
